package com.hctforgreen.greenservice;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.AssignLoginEntity;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.ui.widget.MyCustomDialog;
import com.hctforgreen.greenservice.utils.CheckNetworkUtil;
import com.hctforgreen.greenservice.utils.ContantsUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.LoginInStoreUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.MachineCodeUtil;
import com.hctforgreen.greenservice.utils.ScreenUtil;
import com.hctforgreen.greenservice.utils.ToastUtil;
import com.hctforgreen.greenservice.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * 登录页面
 *
 * @author Tallen Zhai
 */
public class LoginActivity extends ParentActivity {
    private Activity context;
    private int loginStatus = 0;// 登录控制变量
    private LinearLayout cross_code_Layout;
    private EditText edit_cross_code;
    private EditText phoneEt;
    private TextView link_backuppwd;

    private final int topTime = 60 * 10;
    private int Num = topTime;// 倒数时间
    /**
     * 是否停止倒数线程
     */
    private boolean stop = false;
    /**
     * 短信验证唯一码
     */
    private String identity;
    /**
     * 是否验证码登陆
     */
    private boolean isFristlogin = false;

    /**
     * 登录标识，用于判断登录掌上通正式服务器的次数，超过1次则判断为正式服务器宕机
     */
    public int pingCount = 0;
    /**
     * ping百度的结果
     */
    private String checkNetworkResult = null;
    /**
     * false为正式服务器，true为云服务器
     */
    private boolean isClounServer = false;

    /**
     * 390694--2016.5.26添加
     *
     * @category用于判断是否是派工登录异常跳转过来的，true--是派工跳转
     */
    private boolean isDispatching = false;

    private Button loginInBtn;
    private MachineCodeUtil codeUtil;

    private final int REQUEST_PERMISSION_CODE = 2;
    private boolean isAgree;
    //需要申请的权限
    private List<String> finalList;

    //3个相关的权限 --很重要
    String[] checkPermissionArry = new String[]{Manifest.permission.READ_PHONE_STATE};
    boolean[] ifNeed = new boolean[1];
    private final String TAG = "LoginActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        context = this;
        super.onCreate(savedInstanceState);
        super.rightScroll = false;
        setContentView(R.layout.activity_login);

        initSkinLayout();
        initClickEdgehideKeyboard();
        dealLoginCenterLytParams();
        initTitleButtonBar();
        initWindow();

        checkKeyPermission();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //调用ParentActivity中对返回键点击的事件处理
            doubleTouchExit(this);
            return true;
        }
        return false;
    }

    /**
     * 点击边缘隐藏输入法
     */
    private void initClickEdgehideKeyboard() {
        LinearLayout rootLyt = (LinearLayout) findViewById(R.id.lyt_root);
        rootLyt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                KeyboardUtil keyboardUtil = new KeyboardUtil();
                keyboardUtil.hideSoftKeyboard(v);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        new MyCustomDialog().destroyDialog();
    }

    private void dealLoginCenterLytParams() {
        ScreenUtil screenUtil = new ScreenUtil();
        int screenWidth = screenUtil.getScreenWidth(this);

        int loginCenterHeight = (screenWidth * 896 / 640);

        LinearLayout loginCenterLyt = (LinearLayout) findViewById(R.id.lyt_login_center);
        LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
                loginCenterHeight);
        loginCenterLyt.setLayoutParams(params);
    }

    private void initTitleButtonBar() {

    }

    private void initWindow() {
        codeUtil = new MachineCodeUtil(LoginActivity.this);
        phoneEt = (EditText) findViewById(R.id.et_phone);
        loginInBtn = (Button) findViewById(R.id.btn_login_in);
        edit_cross_code = (EditText) findViewById(R.id.edit_cross_code);
        link_backuppwd = (TextView) findViewById(R.id.link_backuppwd);
        cross_code_Layout = (LinearLayout) findViewById(R.id.cross_code_Layout);
        CheckBox autoLoginInCb = (CheckBox) findViewById(R.id.cb_auto_login_in);

        // 派工经由开机密码界面跳转
        Bundle bundle = getIntent().getExtras();
        /*
         * 390694--2016.5.26添加
         * 先判断是否是派工跳转，是再判断bundle的值，
         * 否则先判断bundle的值，6.0系统下bundle的值不为空，则不是派工跳转也会走bundle判断的if方法里
         * 导致掌上通用户在6.0系统下无法自动登录
         */
        isDispatching = getIntent().getBooleanExtra("isDispatching", false);
        if (isDispatching) {
            if (bundle != null) {
                String phone = bundle.getString("phone") != null ? bundle
                        .getString("phone") : "";
                phoneEt.setText(phone);
                phoneEt.setSelection(phoneEt.getText().length());
                LoginInStoreUtil.saveAutoLoginIn(context, false);// 屏蔽自动登陆
            }
        }

        String loginPhone = getIntent().getStringExtra("loginout_phone");
        if (loginPhone != null && !"".equals(loginPhone.trim())) {
            phoneEt.setText(loginPhone);
            phoneEt.setSelection(phoneEt.getText().length());
        }


        // 自动登录
        if (!LoginInStoreUtil.isFirstInstall(LoginActivity.this)
                && LoginInStoreUtil.isAutoLoginIn(LoginActivity.this)) {
            autoLoginInCb.setChecked(true);
            String phone = LoginResultStoreUtil.get(LoginActivity.this).phone;
            phoneEt.setText(phone);
            phoneEt.setSelection(phoneEt.getText().length());
            doLoginin(loginInBtn, phone, codeUtil.getMachineCode(),
                    codeUtil.getIMEICode());
            return;
        }

//		try {
//		/*
//		 * 获取用户的手机号，但并不是每一张SIM卡可以拿到手机号码，这取决于运营商有没有把手机号码的数据写入到SIM卡中
//		 */
//			TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
//			String tel = tm.getLine1Number();//手机号
//			if (tel != null && !tel.trim().equals("")) {
//				if (tel.startsWith("+86")) {
//					tel = tel.substring(3, tel.length());
//				}
//				phoneEt.setText(tel);
//			}
//		}catch(Exception e){
//			e.printStackTrace();
//		}


    }

    //在获取用户的权限后获取手机号码，并且显示在手机号码文本框中
    private void getPhoneNumber() {
        try {
            /*
             * 获取用户的手机号，但并不是每一张SIM卡可以拿到手机号码，这取决于运营商有没有把手机号码的数据写入到SIM卡中
             */
            TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            String tel = tm.getLine1Number();//手机号
            if (tel != null && !tel.trim().equals("")) {
                if (tel.startsWith("+86")) {
                    tel = tel.substring(3, tel.length());
                }
                phoneEt.setText(tel);
                phoneEt.setSelection(phoneEt.getText().length());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //因6.0获取权限方式有所不同，将界面的初始化与控件的监听事件分开 20161205
    private void setListeners() {
        loginInBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //1.校验手机号码
                String sPhone = phoneEt.getText().toString().trim();
                String activeCode = edit_cross_code.getText().toString().trim();
                if (sPhone.equals("")) {
                    Toast.makeText(LoginActivity.this, "请输入手机号码",
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                //2.第一次登录，需要校验验证码等信息
                if (isFristlogin) {
                    if (activeCode.equals("")) {
                        Toast.makeText(LoginActivity.this, "请输入验证码",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (identity == null) {
                        Toast.makeText(LoginActivity.this, "请获取验证码",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                //3.登录服务器
                doLoginin(v, sPhone, codeUtil.getMachineCode(),
                        codeUtil.getIMEICode());

            }
        });

        // 增加帐号变更监听
        phoneEt.addTextChangedListener(new TextWatcher() {

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (cross_code_Layout.getVisibility() == View.VISIBLE) {
                    isFristlogin = false;
                    cross_code_Layout.setVisibility(View.GONE);
                }
            }

        });

        // 获取短信验证
        link_backuppwd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                final MachineCodeUtil codeUtil = new MachineCodeUtil(context);
                String time = String.valueOf(System.currentTimeMillis());
                String a = time.substring(time.length() - 4, time.length());
                String imeiCode = codeUtil.getIMEICode();
                final String identityCode = imeiCode.substring(
                        imeiCode.length() - 4, imeiCode.length())
                        + a;
                final String phone = phoneEt.getText().toString();
                // 把按钮变成不可点击，并且显示倒计时（正在获取）
                link_backuppwd.setClickable(false);
                link_backuppwd.setText("重新获取(" + Num-- + ")");

                new Thread(new Runnable() {
                    public void run() {
                        try {
                            for (int i = topTime; i > 0; i--) {
                                if (i <= 0 || stop) {
                                    break;
                                } else {
                                    handler.sendEmptyMessage(-2);
                                    if (i == 1) {
                                        handler.sendEmptyMessage(-3);
                                    }
                                    Thread.sleep(1000);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                new Thread(new Runnable() {
                    public void run() {
                        Message message = new Message();
                        try {
                            HctController controller = new HctController(
                                    LoginActivity.this);
                            JSONObject json = controller
                                    .getAccountActivateCode(phone, identityCode);
                            if (json.getString("statusCode") != null) {
                                if (!json.getString("statusCode").equals("1")) {
                                    // 获取验证码成功则保存唯一码
                                    identity = identityCode;
                                }
                                message.what = -1;
                                message.obj = json;
                                handler2.sendMessage(message);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    android.content.DialogInterface.OnClickListener click_1 = new android.content.DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            arg0.cancel();
        }
    };

    /**
     * 点击解绑
     */
    protected android.content.DialogInterface.OnClickListener click_2(
            final String phone) {
        return new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, UnbundlingActivity.class);
                if (getIntent().getExtras() != null) {
                    intent.putExtras(getIntent().getExtras());
                }
                intent.putExtra("phone", phone);
                startActivity(intent);
            }
        };
    }

    private void doLoginin(final View loginInBtn, final String phone,
                           final String onlyCode, final String imeiCode) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //自此处需要判断一下权限是否都获得了
            hasCallPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
            hasCameraPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            hasLocationPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
            //只有在三个权限都获取的情况下才能自动登录
            if ((hasCallPermission + hasCameraPermission + hasLocationPermission) != 0) {
                return;
            }
        }
        final ProgressBar loadPb = (ProgressBar) findViewById(R.id.pb_loading);
        loginInBtn.setClickable(false);
        loadPb.setVisibility(View.VISIBLE);

        final CheckBox autoLoginInCb = (CheckBox) findViewById(R.id.cb_auto_login_in);
        MobclickAgent.onEvent(this, "login_time");
        /**
         * 修改友盟jar
         * 去除MobclickAgent.onEventBegin(this, "Account_login");
         * MobclickAgent.onEventEnd(LoginActivity.this, "Account_login");
         * 该方法废除
         * 统计登录时间，需要自己去获取经历的时间，然后将其传出
         */
        //获取当前时间的毫秒值
        final long firstTime = System.currentTimeMillis();

        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                //登陆之后的毫秒值
                long secondTime = System.currentTimeMillis();
                int time = (int) (secondTime - firstTime);
                //使用该方法将时间值传到友盟
                MobclickAgent.onEventValue(context, "Account_login", null, time);

                loadPb.setVisibility(View.GONE);

                HctResult hctResult = new HctResult();

                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        if (pingCount >= 1) { //如果pingCount大于等于1 ，表示登录的是云服务器
                            isClounServer = true;
                            ToastUtil.showToast(LoginActivity.this, R.string.disaster_recovery_login);
                        }

                        hctResult = (HctResult) msg.obj;
                        LoginResultEntity entity = (LoginResultEntity) hctResult.data;

                        if (entity.loginStatus.equals("0")) {//正常登录
                            if (autoLoginInCb.isChecked()) {
                                LoginInStoreUtil.saveAutoLoginIn(
                                        LoginActivity.this, true);
                            } else {
                                LoginInStoreUtil.saveAutoLoginIn(
                                        LoginActivity.this, false);
                                // Log.i("DATA","   "+LoginInStoreUtil.isAutoLoginIn(LoginActivity.this));
                            }
                            //一登录成功就获取到手机号码、personId的值存储起来
                            ContantsUtil.sPhoneNumber = phone;
                            ContantsUtil.sPersonId = entity.personId;
                            Intent intent = new Intent();
                            intent.putExtra("PING_COUNT", pingCount);
                            intent.putExtra("WHICH_SERVER", isClounServer);
                            intent.setClass(LoginActivity.this, MainActivityV2.class);
                            if (getIntent().getExtras() != null) {
                                intent.putExtras(getIntent().getExtras());
                            }
                            intent.putExtra("assignLogin", "false");
                            startActivity(intent);
                            entity.phone = phone;
                            entity.functions += "!101!";// 添加格力小工具
                            LoginResultStoreUtil.save(LoginActivity.this, entity);

                            if (entity.personId.trim().length() > 0
                                    && entity.tags != null
                                    && entity.tags.size() > 0) {
                                JPushInterface.setAliasAndTags(LoginActivity.this,
                                        entity.personId, entity.tags,
                                        new TagAliasCallback() {

                                            @Override
                                            public void gotResult(int arg0, String arg1, Set<String> arg2) {
                                            }
                                        });
                            }
                            pingCount = 0;    //云服务器登录成功后	，把pingCount置为0
                            finish();
                        } else if (entity.loginStatus.equals("5")) {//5：首次登录，需要激活码
                            // phoneEt.setEnabled(false);// 设置帐号不可更改
                            if (isClounServer) {//如果要登录云服务器，则屏蔽获取验证码
                                isFristlogin = false;// 设置需验证码登陆
                                Utils.notice(LoginActivity.this, "",
                                        getResources().getString(R.string.disaster_recovery_get_activitecode),
                                        click_1);
                            } else {
                                isFristlogin = true;// 设置需验证码登陆
                                //20160610--测试发现把这行代码放在else外面是错误的，但还没确定是否要修改
                                //cross_code_Layout.setVisibility(View.VISIBLE);
                            }
                            loginInBtn.setClickable(true);
                            cross_code_Layout.setVisibility(View.VISIBLE);
                        } else if (entity.loginStatus.equals("3")) {// 3：用户已绑定其他手机
                            loginInBtn.setClickable(true);

                            if (isClounServer) {
                                Utils.notice(LoginActivity.this, "",
                                        getResources().getString(R.string.disaster_recovery_bind),
                                        click_1);
                            } else {//如果是正式服务器，则可以解绑
                                Utils.notice(LoginActivity.this, "", entity.loginMsg,
                                        R.string.dlg_cancel,
                                        R.string.get_cross_code_apply, click_1,
                                        click_2(phone));
                            }


                        } else if (entity.loginStatus.equals("7")) {// 验证码错误
                            loginInBtn.setClickable(true);
                            Toast.makeText(LoginActivity.this, entity.loginMsg,
                                    Toast.LENGTH_SHORT).show();
                        } else if (entity.loginStatus.equals("1")) {//1：用户不存在；
                            loginInBtn.setClickable(true);
                            Toast.makeText(LoginActivity.this, entity.loginMsg,
                                    Toast.LENGTH_SHORT).show();
                        } else if (entity.loginStatus.equals("2")) {// 2：用户未激活 ；
                            loginInBtn.setClickable(true);
                            Toast.makeText(LoginActivity.this, entity.loginMsg,
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            //2017.1.5--390694   添加灾备逻辑
                            pingCount = pingCount + 1;
                            //ping百度，登录云服务器
                            loginCloudPlatforms(phone, onlyCode, imeiCode);
                            loginInBtn.setClickable(true);
                        }
                        break;

                    case HctConstants.STATUS_FAILD:
                        // assignLogin(loginInBtn, phone, new LoginResultEntity());

                        // 2016-4-19，做灾备功能时屏蔽的原始代码
                        // Toast.makeText(LoginActivity.this,
                        // getString(R.string.net_error_hint),
                        // Toast.LENGTH_SHORT).show();
                        // loginInBtn.setClickable(true);

                        //2016.5.6--390694   添加灾备逻辑
                        pingCount = pingCount + 1;
                        //ping百度，登录云服务器
                        loginCloudPlatforms(phone, onlyCode, imeiCode);

                        loginInBtn.setClickable(true);
                        break;
                }
            }
        };

        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    String activeCode = edit_cross_code.getText().toString()
                            .trim();

                    HctController controller = new HctController(
                            LoginActivity.this);
                    HctResult result = controller.appLogin(phone, onlyCode,
                            imeiCode, isFristlogin == true ? activeCode : "",
                            isFristlogin == true ? identity : "", pingCount);

                    // HctResult hctResult = controller.assignLogin(phone);
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }

                } catch (Exception e) {
                    message.what = HctConstants.STATUS_FAILD;
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();

    }

    //登录云服务器
    public void loginCloudPlatforms(final String phone,
                                    final String onlyCode, final String imeiCode) {
        if (pingCount >= 2) {
            ToastUtil
                    .showToast(
                            LoginActivity.this,
                            R.string.can_not_linkServer);
            pingCount = 0;
            return;
        }

        if (CheckNetworkUtil.checkNetwork(LoginActivity.this)) {
            // ping百度成功表示网络可以上网，这时访问云服务器
            if (startToCheckNetwork()) {
                doLoginin(loginInBtn, phone, onlyCode, imeiCode);
                Log.i("DATA", " 登录云服务器    " + "");

            } else {
                pingCount = 0;
                ToastUtil
                        .showToast(
                                LoginActivity.this,
                                R.string.disaster_recovery_unavailable_network);

            }

        } else {
            pingCount = 0;
            ToastUtil.showToast(LoginActivity.this, R.string.disaster_recovery_link_network);
        }
    }

    /**
     * 判断派工权限
     *
     * @param loginInBtn
     * @param phone
     * @param loginEntity
     */
    private void assignLogin(final View loginInBtn, final String phone,
                             final LoginResultEntity loginEntity) {

        final ProgressBar loadPb = (ProgressBar) findViewById(R.id.pb_loading);
        loginInBtn.setClickable(false);
        loadPb.setVisibility(View.VISIBLE);

        final CheckBox autoLoginInCb = (CheckBox) findViewById(R.id.cb_auto_login_in);
        //MobclickAgent.onEvent(this, "Account_login");
        /**
         * 2016 11 28 390778
         * 修改友盟jar
         * 去除MobclickAgent.onEventBegin(this, "Account_login");
         * MobclickAgent.onEventEnd(LoginActivity.this, "Account_login");
         * 该方法废除
         * 统计登录时间，需要自己去获取经历的时间，然后将其传出
         */
        //获取当前时间的毫秒值
//		final long firstTime=System.currentTimeMillis();

        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                //登陆之后的毫秒值
//				long secondTime=System.currentTimeMillis();
//				int time = (int) (secondTime - firstTime);
////				使用该方法将时间值传到友盟
//				MobclickAgent.onEventValue(context,"login_time",null,time);

                loginInBtn.setClickable(true);
                loadPb.setVisibility(View.GONE);

                HctResult hctResult = new HctResult();
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        hctResult = (HctResult) msg.obj;
                        AssignLoginEntity entity = (AssignLoginEntity) hctResult.data;
                        if (entity != null && "true".equals(entity.Result)) {// 只是派工账号
                            loginEntity.phone = phone;
                            loginEntity.functions = LoginResultEntity.FUNCTION_TAG
                                    + "100" + LoginResultEntity.FUNCTION_TAG;
                            LoginResultStoreUtil.save(LoginActivity.this,
                                    loginEntity);
                            // if (autoLoginInCb.isChecked()) {
                            // LoginInStoreUtil.saveAutoLoginIn(
                            // LoginActivity.this, true);
                            // } else {
                            LoginInStoreUtil.saveAutoLoginIn(LoginActivity.this,
                                    false);
                            // }
                            Intent intent = new Intent();
                            intent.setClass(LoginActivity.this,
                                    MainActivityV2.class);
                            if (getIntent().getExtras() != null) {
                                intent.putExtras(getIntent().getExtras());
                            }
                            startActivity(intent);
                            finish();
                        } else {
                            if (loginEntity != null
                                    && !TextUtils.isEmpty(loginEntity.loginMsg)) {
                                Toast.makeText(LoginActivity.this,
                                        loginEntity.loginMsg, Toast.LENGTH_SHORT)
                                        .show();
                            } else {
                                Toast.makeText(LoginActivity.this,
                                        getString(R.string.net_error_hint),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                        break;

                    case HctConstants.STATUS_FAILD:
                        if (loginEntity != null
                                && !TextUtils.isEmpty(loginEntity.loginMsg)) {
                            Toast.makeText(LoginActivity.this,
                                    loginEntity.loginMsg, Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            Toast.makeText(LoginActivity.this,
                                    getString(R.string.net_error_hint),
                                    Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        };

        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(
                            LoginActivity.this);
                    HctResult result = controller.assignLogin(phone);

                    // HctResult hctResult = controller.assignLogin(phone);

                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }

                } catch (Exception e) {
                    message.what = HctConstants.STATUS_FAILD;
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();

    }

    @SuppressLint("HandlerLeak")
    Handler handler2 = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -1) {
                JSONObject json = (JSONObject) msg.obj;
                try {
                    if (json.getString("statusCode").equals("1")) {
                        // 短信发送失败，停止倒数
                        stop = true;
                        link_backuppwd
                                .setText(getString(R.string.get_cross_code_submit_link));
                        link_backuppwd.setClickable(true);
                        Num = topTime;

                    }
                    String accountMsg = json.getString("accountMsg");
                    Toast.makeText(context, accountMsg, Toast.LENGTH_SHORT)
                            .show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (msg.what == -4) {
                // 返回解绑信息
                JSONObject json = (JSONObject) msg.obj;
                try {
                    String accountMsg = json.getString("accountMsg");
                    if (json.getString("statusCode").equals("1")) {
                        Toast.makeText(context, accountMsg, Toast.LENGTH_SHORT)
                                .show();
                    } else if (json.getString("statusCode").equals("0")) {
                        Utils.notice(context, "", accountMsg, click_1);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -2) {
                link_backuppwd.setText("重新获取(" + Num-- + ")");
            } else if (msg.what == -3) {
                // 填写短信时限结束
                link_backuppwd
                        .setText(getString(R.string.get_cross_code_submit_link));
                link_backuppwd.setClickable(true);
                Num = topTime;
                identity = null;// 时限结束，将唯一码重新设为null
            }
        }
    };

    /**
     * 检查网络
     */
    public boolean startToCheckNetwork() {
        for (int count = 0; count < 3; count++) {
            if (CheckNetworkUtil.isNetworkAvailable()) {
                return true;
            }

        }
        return false;
    }


    /**
     * 危险权限有：
     * android.permission.READ_CONTACTS 读取联系人
     * android.permission.READ_PHONE_STATE 读取电话状态
     * android.permission.CALL_PHONE 拨打电话
     * android.permission.READ_CALL_LOG 读取通话记录（暂不申请）
     * android.permission.WRITE_CALL_LOG 修改通话记录（暂不申请）
     * android.permission.CAMERA 获取拍照权限
     * android.permission.ACCESS_FINE_LOCATION 通过gps获取定位权限
     * android.permission.ACCESS_COARSE_LOCATION 通过WiFi和移动基站获取定位权限
     * android.permission.READ_EXTERNAL_STORAGE 读取内存卡 下载资料，设置，
     * android.permission.WRITE_EXTERNAL_STORAGE 写内存卡
     * android.permission.RECORD_AUDIO 录音权限（暂不申请）
     */

    private final int REQUEST_CALL_PERMISSION_CODE = 3;
    private final int REQUEST_CAMERA_PERMISSION_CODE = 4;
    private final int REQUEST_LOCATION_PERMISSION_CODE = 5;

    private int hasCallPermission;
    private int hasCameraPermission;
    private int hasLocationPermission;

    //在此处申请关键权限的获取
    private void checkKeyPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            getPhoneNumber();
            setListeners();
            return;
        }
        hasCallPermission = ActivityCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.READ_CONTACTS);
        if (hasCallPermission != PackageManager.PERMISSION_GRANTED) {
            //获取联系人、读取通话记录、拨打电话
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CALL_PERMISSION_CODE);
        } else {
            //获取到了读取通话的系列权限
            hasCameraPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_CODE);
            } else {
                //获取到了相机权限
                hasLocationPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
                if (hasLocationPermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION_CODE);
                } else {
                    //获取到了定位权限 即三项权限都获取了
                    getPhoneNumber();
                    setListeners();
                }

            }
        }
    }


    /**
     * 通过调用6.0系统权限申请结果的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CALL_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //用户同意通话权限
                //检查相机权限
                if (ActivityCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //没有相机权限
                    ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_CODE);
                }
            } else {
                showDialog(Manifest.permission.READ_CONTACTS);
            }
        }


        if (requestCode == REQUEST_CAMERA_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //用户同意相机权限
                //检查定位权限
                if (ActivityCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    //没有定位权限
                    ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION_CODE);
                }
            } else {
                showDialog(Manifest.permission.CAMERA);
            }
        }

        if (requestCode == REQUEST_LOCATION_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //用户同意定位权限
                setListeners();
                getPhoneNumber();
            } else {
                showDialog(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
        }

    }

    //当系统权限弹框弹后，用户不同意则使用该弹框
    private void showDialog(String permission) {
        String content = "";
        if (permission.equals(Manifest.permission.CAMERA)) {
            content = getString(R.string.camera);
        } else if (permission.equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
            content = getString(R.string.location);
        } else if (permission.equals(Manifest.permission.READ_CONTACTS)) {
            content = getString(R.string.contacts);
        }
        new MyCustomDialog().showAlert(this, getString(R.string.apply_for_permission), getString(R.string.permission_tip) + content + getString(R.string.permission), getString(R.string.set_permission_now), getString(R.string.dont_set), new MyCustomDialog.OnAlertSelected() {
            @Override
            public void onClick(int whichButton) {
                if (whichButton == MyCustomDialog.YES) {
                    //打开系统设置
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.MAIN");
                    intent.setClassName("com.android.settings", "com.android.settings.ManageApplications");
                    startActivity(intent);
                    System.exit(0);
                } else {
                    //关闭APP
                    System.exit(0);
                }

            }
        });
    }
}
